PurchasesDeal = new Object();
var formpanel;
// custom Vtype for vtype:'Rate'
Ext.apply(Ext.form.field.VTypes, {
	Rate : function(v) {
		return /^100(\.0{0,2})? *%?$|^\d{1,2}(\.\d{1,2})? *%?$/.test(v);
	},
	RateText : 'Invalid Rate',
	RateMask : /[\d\.%]/i
});

var calculationtype = "DEAL";

var searchDeal = Ext.create('Ext.data.Store', {
	fields : [ 'id', 'status', 'name', 'insType', 'listedInsCode', 'insCode', 'dealValue', 'maturityValue', 'maturityDate', 'valueDate', 'placementFee', 'secMarket',
			'secSellerName', 'secSellerBankNo', 'couponDates', 'primaryDealer', 'issuer', 'couponRate', 'couponFreq', 'rateinterest', 'rateResetPeriod', 'resetDate', 'benchMark',
			'floorValue', 'ceilingValue', 'withholdingTax', 'withholdingTaxRate', 'dayBasis', 'denominalMinVal', 'user', 'dealCode', 'fund', 'params', 'settlementCode',
			'delevarymethode', 'dealerCode' ]
});

Ext.define('Collateral', {
	extend : 'Ext.data.Model',
	fields : [ {
		name : 'instrumentType',
		type : 'string'
	}, {
		name : 'instrumentNo',
		type : 'string'
	}, {
		name : 'value',
		type : 'float'
	}, {
		name : 'couponDate',

		dateFormat : 'd/m/Y'
	} ]
});

var instrumentStore = new Ext.data.Store({
	fields : [ 'id', 'couponRate', 'label', 'issuer', 'minDenominal', 'listedInsCode', 'valueDate', 'maturityDate', 'status', 'issuerName' ],
	storeId : 'recPurchInsStore'
});

var instrumentTypes = Ext.create('Ext.data.Store', {
	fields : [ 'type', 'issuer', 'interest', 'withholdTax', 'coupon', 'couponDates', 'couponFreq', 'dayBasis', 'script', 'denominal', 'listed' ]
});

var benchMarkStore = Ext.create('Ext.data.Store', {
	fields : [ 'name' ],
	data : [ {
		"name" : "BenchMark 1"
	}, {
		"name" : "BenchMark 2"
	}, {
		"name" : "BenchMark 3"
	}, {
		"name" : "BenchMark 4"
	} ]
});

PurchasesDeal.getBasicFieldSet = function() {

	var funds = Ext.create('Ext.data.Store', {
		fields : [ {
			name : 'id',
			type : 'int'
		}, {
			name : 'fundName',
			type : 'string'
		}, {
			name : 'fundCode',
			type : 'string'
		} ],
		storeId : 'dealFundsStore'
	});

	return Ext.create('Ext.form.FieldSet', {
		title : 'Basic',
		defaults : {
			anchor : '100%'
		},
		items : [ {
			xtype : 'label',
			id : 'recPurchParamLbl',
			hidden : true,
			text : ''
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ Ext.create('Ext.form.ComboBox', {
				name : 'fund',
				fieldLabel : 'Fund<span style="color:red">*</span>',
				store : funds,
				queryMode : 'local',
				flex : 1,
				labelWidth : 120,
				id : 'recPurchaseFund',
				padding : '0 5 0 0',
				valueField : 'id',
				displayField : 'fundName',
				autoScroll : true,
				allowBlank : false,
				blankText : 'Please select the Fund',
				msgTarget : 'under',
				editable : false
			}), {
				xtype : 'textfield',
				name : 'name',
				id : 'recDealInsName',
				fieldLabel : 'Name<span style="color:red">*</span>',
				flex : 1,
				allowBlank : false,
				padding : '0 5 0 0'
			} ]
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'datefield',
				fieldLabel : 'Value Date<span style="color:red">*</span>',
				id : 'recPurchValueDt',
				allowBlank : false,
				flex : 1,
				name : 'valueDate',
				labelWidth : 120,
				padding : '0 5 0 0',
				blankText : 'Please select a Value Date',
				msgTarget : 'under',
				format : 'd/m/Y',
				emptyText : 'DD/MM/YYYY',
				listeners : {
					'change' : {
						fn : function(field, newVal, oldVal) {
							var dfMaturityDate = Ext.getCmp('recPurchMaturityDt');
							if (dfMaturityDate.getValue() != null) {
								var lblMaturityDate = Ext.getCmp('recPurchDuration');
								if (this.getValue() > dfMaturityDate.getValue()) {
									Ext.MessageBox.alert('Error', 'Value Date cannot be greater than Maturity Date.');
									this.setValue(null);
									lblMaturityDate.setValue('');
								} else {
									var durationDays = (dfMaturityDate.getValue() - this.getValue()) / 86400000;
									lblMaturityDate.setValue('Duration: '.concat(durationDays.toString().concat(' days.')));
								}
								if (calculationtype == "DEAL")
									PurchasesDeal.setMatVal();
								else
									PurchasesDeal.setMatValByMaturity();
							}
						}
					}
				}
			}, {
				xtype : 'datefield',
				fieldLabel : 'Matured Date<span style="color:red">*</span>',
				id : 'recPurchMaturityDt',
				allowBlank : false,
				flex : 1,
				name : 'maturityDate',
				padding : '0 5 0 0',
				blankText : 'Please select a Matured Date',
				msgTarget : 'under',
				format : 'd/m/Y',
				emptyText : 'DD/MM/YYYY',
				minValue : new Date(),
				listeners : {
					'change' : {
						fn : function(field, newVal, oldVal) {
							var dfValueDate = Ext.getCmp('recPurchValueDt');
							if (dfValueDate.getValue() != null) {
								var lblValueDate = Ext.getCmp('recPurchDuration');
								if (dfValueDate.getValue() > this.getValue()) {
									Ext.MessageBox.alert('Error', 'Maturity Date cannot be smaller than Value Date.');
									this.setValue(null);
									lblValueDate.setValue('');
								} else {
									var durationDays = (this.getValue() - dfValueDate.getValue()) / 86400000;
									lblValueDate.setValue('Duration: '.concat(durationDays.toString().concat(' days.')));
								}
								if (calculationtype == "DEAL")
									PurchasesDeal.setMatVal();
								else
									PurchasesDeal.setMatValByMaturity();
							}
						}
					}
				}
			} ]
		}, {
			xtype : 'displayfield',
			id : 'recPurchDuration'
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'combo',
				fieldLabel : 'Delevary Method',
				store : CommenStore.delevaryMethodStore,
				valueField : 'id',
				flex : 1,
				labelWidth : 120,
				name : 'delevarymethode',
				padding : '0 5 0 0',
				displayField : 'code',
				tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{code} - <b>{description}</b><br/></div>', '</tpl>'),
				displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{code} - {description}', '</tpl>'),
				listeners : {
					change : function(combo, record, index) {
						if (combo.getValue() == "" || combo.getValue() == "&nbsp;" || combo.getValue == 0) {
							combo.setValue(null);
						}
					}
				}
			}, {
				xtype : 'combo',
				fieldLabel : 'Dealer',
				store : CommenStore.dealersStore,
				valueField : 'id',
				flex : 1,
				padding : '0 5 0 0',
				name : 'dealerCode',
				displayField : 'code',
				tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{code} - <b>{name}</b><br/></div>', '</tpl>'),
				displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{code} - {name}', '</tpl>'),
				listeners : {
					change : function(combo, record, index) {
						if (combo.getValue() == "" || combo.getValue() == "&nbsp;" || combo.getValue == 0) {
							combo.setValue(null);
						}
					}
				}
			} ]
		}, {
			xtype : 'combo',
			labelWidth : 120,
			fieldLabel : 'Settlement Method',
			store : CommenStore.settlmentStore,
			valueField : 'id',
			anchor : '50%',
			name : 'settlementCode',
			padding : '0 10 0 0',
			displayField : 'code',
			tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{code} - <b>{description}</b><br/></div>', '</tpl>'),
			displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{code} - {description}', '</tpl>'),
			listeners : {
				change : function(combo, record, index) {
					if (combo.getValue() == "" || combo.getValue() == "&nbsp;" || combo.getValue == 0) {
						combo.setValue(null);
					}
				}
			}
		} ]
	});
};

PurchasesDeal.getInstrumentFieldSet = function() {

	Ext.define('InstrumentTypePurch', {
		extend : 'Ext.data.Model',
		fields : [ {
			name : 'id',
			type : 'int'
		}, {
			name : 'instrumentName',
			type : 'string'
		}, {
			name : 'istrumentType',
			type : 'int'
		}, {
			name : 'scripts',
			type : 'int'
		}, {
			name : 'denominals',
			type : 'int'
		}, {
			name : 'listed',
			type : 'int'
		}, {
			name : 'withholdingTax',
			type : 'string'
		}, {
			name : 'interestRate',
			type : 'string'
		}, {
			name : 'interestType',
			type : 'string'
		}, {
			name : 'dayBasis',
			type : 'string'
		}, {
			name : 'couponAvailability',
			type : 'int'
		}, {
			name : 'cuponFrequency',
			type : 'int'
		}, {
			name : 'shortMaturable',
			type : 'int'
		}, {
			name : 'calculationInput',
			type : 'int'
		} ]
	});

	var instrumentTypeStore = new Ext.data.Store({
		model : 'InstrumentTypePurch',
		storeId : 'recPurchInsTypeStore'
	});

	Ext.Ajax.request({
		url : 'getInstrumentTypes.action',
		success : function(response) {
			var obj = Ext.decode(response.responseText);
			instrumentTypeStore.loadRawData(obj.instrumentTypeList);
		}
	});

	return Ext.create('Ext.form.FieldSet', {
		title : 'Instrument',
		defaults : {
			anchor : '100%'
		},
		items : [ {
			xtype : 'label',
			flex : 1,
			id : 'recDealDealID',
			style : 'font-weight:600;margin-top:15px;',
			text : 'Deal ID: ',
			hidden : true
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'combo',
				name : 'insType',
				id : 'recDealInstrumentType',
				fieldLabel : 'Instrument Type<span style="color:red">*</span>',
				labelWidth : 120,
				queryMode : 'local',
				store : instrumentTypeStore,
				valueField : 'id',
				displayField : 'instrumentName',
				flex : 1,
				padding : '0 5 0 0',
				autoScroll : true,
				allowBlank : false,
				blankText : 'Select the Instrument Type',
				msgTarget : 'under',
				editable : false,
				listeners : {
					select : {
						fn : function(combo, value) {
							var record = instrumentTypeStore.getAt(instrumentTypeStore.find('id', combo.getValue()));
							Ext.getCmp('recDealInstrumentCodeCombo').clearValue();
							Ext.getCmp('recPurchaseFund').clearValue();
							PurchasesDeal.fieldDisableByInstrumentType(record);
							Ext.Ajax.request({
								url : 'getFundsForDealInsType.action',
								params : {
									querry : 'PURCH',
									querryTwo : record.get('id')
								},
								success : function(response) {
									var obj = Ext.decode(response.responseText);
									Ext.data.StoreManager.lookup('dealFundsStore').loadRawData(obj.fundList);
								}
							});
						}
					},
					change : function(list, record) {
						if (record) {
							var record1 = instrumentTypeStore.getAt(instrumentTypeStore.find('id', list.getValue()));
							PurchasesDeal.fieldDisableByInstrumentType(record1);
							Ext.Ajax.request({
								url : 'getFundsForDealInsType.action',
								params : {
									querry : 'PURCH',
									querryTwo : list.getValue()
								},
								success : function(response) {
									var obj = Ext.decode(response.responseText);
									Ext.data.StoreManager.lookup('dealFundsStore').loadRawData(obj.fundList);
								}
							});
						}
					}
				}
			}, {
				xtype : 'displayfield',
				flex : 1,
				id : 'recDealListedLabel',
				value : '',
				style : 'font-weight:600;'
			} ]
		}, {
			xtype : 'combo',
			name : 'listedInsCode',
			id : 'recDealInstrumentCodeCombo',
			fieldLabel : 'Instrument Code<span style="color:red">*</span>',
			labelWidth : 120,
			store : instrumentStore,
			queryMode : 'local',
			valueField : 'listedInsCode',
			displayField : 'listedInsCode',
			anchor : '50%',
			padding : '0 5 0 0',
			style : 'margin-top:10px;',
			autoScroll : true,
			allowBlank : false,
			blankText : 'Select the Instrument Code',
			msgTarget : 'under',
			editable : false,
			hidden : true,
			tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{listedInsCode}<br/></div>', '</tpl>'),
			displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{listedInsCode}', '</tpl>'),
			listConfig : {
				listeners : {
					itemclick : function(list, record) {
						PurchasesDeal.setInstrumentValue(record);
					}
				}
			}
		}, {
			xtype : 'textfield',
			name : 'insCode',
			fieldLabel : 'Instrument Code<span style="color:red">*</span>',
			labelWidth : 120,
			id : 'recDealInstrumentCodeText',
			allowBlank : false,
			anchor : '50%',
			padding : '0 5 0 0',
			style : 'margin-top:10px;',
			blankText : 'Instrument Code is required',
			msgTarget : 'under',
			listeners : {
				'blur' : function(field) {
					find = instrumentStore.find('code', field.getValue());
					if (find != -1) {
						Ext.Msg.alert(field.getValue() + " is already used!");
						this.reset();
					}
				}
			}
		}, {
			xtype : 'displayfield',
			flex : 1,
			id : 'recDealStatusLbl',
			style : 'font-weight:600;margin-top:15px;',
			text : 'Deal ID: ',
			hidden : true
		} ]
	});
};

PurchasesDeal.fieldDisableByInstrumentType = function(record) {

	if (record != null || record != "") {
		var form = Ext.getCmp('instrumentdetails');
		if (record.get('dayBasis') == 'Vary') {
			Ext.getCmp('recDealDayBasis').enable();
		} else {
			Ext.getCmp('recDealDayBasis').disable();
		}

		console.log(record.get('interestRate'));
		if (record.get('interestRate') == "Fixed") {
			Ext.getCmp('recPurchFloatField1').hide();
			Ext.getCmp('recPurchFloatField2').hide();
			Ext.getCmp('recPurchFloatField1').disable();
			Ext.getCmp('recPurchFloatField2').disable();
			Ext.getCmp('RecPurchResetPeriod').allowBlank = true;
			Ext.getCmp('recPurchFloatResetDt').allowBlank = true;
			Ext.getCmp('recPurchFloor').allowBlank = true;
			Ext.getCmp('recPurchCeiling').allowBlank = true;
			Ext.getCmp('RecPurchResetPeriod').disable();
			Ext.getCmp('recPurchFloatResetDt').disable();
			Ext.getCmp('recPurchFloor').disable();
			Ext.getCmp('recPurchCeiling').disable();
		} else {
			Ext.getCmp('recPurchFloatField1').show();
			Ext.getCmp('recPurchFloatField2').show();
			Ext.getCmp('recPurchFloatField1').enable();
			Ext.getCmp('recPurchFloatField2').enable();
			Ext.getCmp('RecPurchResetPeriod').allowBlank = false;
			Ext.getCmp('recPurchFloatResetDt').allowBlank = false;
			Ext.getCmp('recPurchFloor').allowBlank = false;
			Ext.getCmp('recPurchCeiling').allowBlank = false;
			Ext.getCmp('RecPurchResetPeriod').enable();
			Ext.getCmp('recPurchFloatResetDt').enable();
			Ext.getCmp('recPurchFloor').enable();
			Ext.getCmp('recPurchCeiling').enable();
		}
		form.getForm().loadRecord(record);

		Ext.getCmp('recDealCouponFreq').setValue(record.get('cuponFrequency'));

		var lblListed = Ext.getCmp('recDealListedLabel');
		var comboInsCode = Ext.getCmp('recDealInstrumentCodeCombo');
		var tfInsCode = Ext.getCmp('recDealInstrumentCodeText');

		if (record.get('listed') == 1) {
			lblListed.setValue('Listed Instrument');
			tfInsCode.disable();
			tfInsCode.hide();
			comboInsCode.show();
			comboInsCode.enable();
			Ext.Ajax.request({
				url : 'getInstrumentsByType.action',
				params : {
					"instrumentTypeId" : record.get('id')
				},
				success : function(response) {
					var obj = Ext.decode(response.responseText);
					instrumentStore.removeAll();
					instrumentStore.loadRawData(obj.instrumentDtos);
				}
			});

		} else {
			lblListed.setValue('Non-Listed Instrument');
			comboInsCode.hide();
			comboInsCode.disable();
			tfInsCode.show();
			tfInsCode.enable();
		}

		var maturityValuetf = Ext.getCmp('recDealMaturityValue');
		var dealValuetf = Ext.getCmp('recPurchDealVal');
		if (record.get('calculationInput') == 2) {
			dealValuetf.setReadOnly(true);
			maturityValuetf.setReadOnly(false);
			calculationtype = "MATURITY";
		} else {
			maturityValuetf.setReadOnly(true);
			dealValuetf.setReadOnly(false);
			calculationtype = "DEAL";
		}
	}

};

PurchasesDeal.getDealFieldSet = function() {
	return Ext.create('Ext.form.FieldSet', {
		title : 'Deal',
		defaults : {
			anchor : '100%'
		},
		items : [ {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'textfield',
				id : 'recPurchDealVal',
				minValue : 0,
				name : 'dealValue',
				fieldLabel : 'Deal Value<span style="color:red">*</span>',
				allowBlank : false,
				blankText : 'Please enter the Deal Amount',
				msgTarget : 'under',
				flex : 1,
				padding : '0 5 5 0',
				maskRe : /[\d\,.]/,
				listeners : {
					blur : function() {
						this.setRawValue(Ext.util.Format.number(this.value.replace(/,/g, ''), '0,000.0000'));
						if (calculationtype == "DEAL")
							PurchasesDeal.setMatVal();
						else
							PurchasesDeal.setMatValByMaturity();
					},
					render : function(p) {
						this.setRawValue(Ext.util.Format.number(this.value, '0,000.0000'));
					}
				}
			}, {
				xtype : 'textfield',
				minValue : 0,
				name : 'placementFee',
				id : 'recDealPlacementFee',
				fieldLabel : 'Placement Fee<span style="color:red">*</span>',
				allowBlank : false,
				blankText : 'Please enter the Placement Fee',
				msgTarget : 'under',
				flex : 1,
				padding : '0 5 5 0',
				maskRe : /[\d\,.]/,
				listeners : {
					blur : function() {
						this.setRawValue(Ext.util.Format.number(this.value.replace(/,/g, ''), '0,000.0000'));
					},
					render : function(p) {
						this.setRawValue(Ext.util.Format.number(this.value, '0,000.0000'));
					}
				}
			} ]
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'checkboxfield',
				boxLabel : 'Secondary Market',
				id : 'recPurchSecMarket',
				name : 'secMarket',
				inputValue : 1,
				flex : 1,
				padding : '0 5 5 0',
				listeners : {
					change : {
						fn : function(object, Value) {
							if (Value) {
								var ssname = Ext.ComponentQuery.query('#secSellerName')[0];
								ssname.enable();
								var ssbank = Ext.ComponentQuery.query('#secSellerBank')[0];
								ssbank.enable();
							} else {
								var ssname = Ext.ComponentQuery.query('#secSellerName')[0];
								ssname.disable();
								var ssbank = Ext.ComponentQuery.query('#secSellerBank')[0];
								ssbank.disable();
							}
						}
					}
				}
			}, {
				xtype : 'textfield',
				minValue : 0,
				id : 'recDealMaturityValue',
				fieldLabel : 'Maturity Value<span style="color:red">*</span>',
				allowBlank : false,
				name : 'maturityValue',
				readOnly : true,
				msgTarget : 'under',
				flex : 1,
				padding : '0 5 5 0',
				maskRe : /[\d\,.]/,
				listeners : {
					blur : function() {
						this.setRawValue(Ext.util.Format.number(this.value.replace(/,/g, ''), '0,000.0000'));
						if (calculationtype == "DEAL")
							PurchasesDeal.setMatVal();
						else
							PurchasesDeal.setMatValByMaturity();
					},
					render : function(p) {
						this.setRawValue(Ext.util.Format.number(this.value, '0,000.0000'));
					}
				}
			} ]
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			style : 'margin-top:10px;',
			items : [ {
				xtype : 'textfield',
				name : 'secSellerName',
				id : 'secSellerName',
				fieldLabel : "Seller's Name",
				disabled : true,
				flex : 1,
				padding : '0 5 5 0'
			}, {
				xtype : 'textfield',
				name : 'secSellerBankNo',
				id : 'secSellerBank',
				fieldLabel : "Bank No",
				disabled : true,
				flex : 1,
				padding : '0 5 5 0'
			} ]
		} ]
	});
};

PurchasesDeal.getInstrumentDetailFieldSet = function() {

	var cpnDtStore = Ext.create('Ext.data.Store', {
		storeId : 'couponDatesStore',
		fields : [ {
			name : 'couponDate',
			type : 'date',
			dateFormat : 'd/m/Y'
		} ]
	});

	var primaryDealerStore = Ext.create('Ext.data.Store', {
		storeId : 'primaryDealersStore',
		fields : [ {
			name : 'id',
			type : 'int'
		}, {
			name : 'name',
			type : 'string'
		}, {
			name : 'code',
			type : 'string'
		}, {
			name : 'creditRating',
			type : 'string'
		} ]
	});

	var issuersStore = Ext.create('Ext.data.Store', {
		storeId : 'issuersStore',
		fields : [ {
			name : 'id',
			type : 'int'
		}, {
			name : 'name',
			type : 'string'
		}, {
			name : 'code',
			type : 'string'
		}, {
			name : 'creditRating',
			type : 'string'
		} ]
	});

	Ext.Ajax.request({
		url : 'getPrimaryDealers.action',
		success : function(response) {
			var obj = Ext.decode(response.responseText);
			primaryDealerStore.loadRawData(obj.issuers);
		}
	});

	Ext.Ajax.request({
		url : 'getIssuers.action',
		success : function(response) {
			var obj = Ext.decode(response.responseText);
			issuersStore.loadRawData(obj.issuerList);
		}
	});

	var valDate = Ext.getCmp('recPurchValueDt');
	var matDate = Ext.getCmp('recPurchMaturityDt');

	return Ext.create('Ext.form.FieldSet', {
		title : 'Instrument Details',
		defaults : {
			anchor : '100%'
		},
		items : [ {
			xtype : 'form',
			bodyBorder : false,
			frame : true,
			border : false,
			id : 'instrumentdetails',
			items : [ {
				xtype : 'fieldcontainer',
				layout : 'hbox',
				items : [ {
					xtype : 'radiogroup',
					fieldLabel : 'Instrument Type',
					labelWidth : 110,
					columns : 1,
					flex : 1,
					padding : '0 5 0 0',
					vertical : true,
					disabled : true,
					items : [ {
						boxLabel : 'Government',
						name : 'istrumentType',
						inputValue : '1',
						checked : true,
						id : 'cbIssuerGovernment',
						listeners : {
							change : function(field, newValue, oldValue) {
								if (newValue) {
									Ext.getCmp('recordDealPrimDealer').setDisabled(false);
									Ext.getCmp('recordDealPrimDealer').allowBlank = false;
									Ext.getCmp('recordDealIssuer').setDisabled(true);
									Ext.getCmp('recordDealIssuer').allowBlank = true;
								}
							}
						}
					}, {
						boxLabel : 'Other',
						name : 'istrumentType',
						inputValue : '0',
						id : 'cbIssuerOther',
						listeners : {
							change : function(field, newValue, oldValue) {
								if (newValue) {
									Ext.getCmp('recordDealPrimDealer').setDisabled(true);
									Ext.getCmp('recordDealPrimDealer').allowBlank = true;
									Ext.getCmp('recordDealIssuer').setDisabled(false);
									Ext.getCmp('recordDealIssuer').allowBlank = false;
								}
							}
						}
					} ]
				}, {
					xtype : 'fieldcontainer',
					flex : 1,
					layout : {
						type : 'vbox',
					},
					items : [ {
						xtype : 'combo',
						fieldLabel : 'Primary Dealer',
						store : primaryDealerStore,
						valueField : 'id',
						name : 'primaryDealer',
						queryMode : 'local',
						id : 'recordDealPrimDealer',
						autoScroll : true,
						anchor : '50%',
						editable : false,
						tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item"><b>{code}</b>-{name}<br/></div>', '</tpl>'),
						displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{name}', '</tpl>')
					}, {
						xtype : 'combo',
						fieldLabel : 'Issuer',
						store : issuersStore,
						valueField : 'id',
						name : 'issuer',
						anchor : '50%',
						queryMode : 'local',
						id : 'recordDealIssuer',
						autoScroll : true,
						editable : false,
						disabled : true,
						tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item"><b>{code}</b>-{name}<br/></div>', '</tpl>'),
						displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{name}', '</tpl>')
					} ]
				} ]
			}, {
				xtype : 'fieldcontainer',
				layout : 'hbox',
				items : [ {
					xtype : 'radiogroup',
					fieldLabel : 'Coupon Availability',
					labelWidth : 110,
					columns : 3,
					columnWidth : 5,
					flex : 1,
					padding : '0 5 0 0',
					vertical : true,
					disabled : true,
					items : [ {
						boxLabel : 'No',
						name : 'couponAvailability',
						inputValue : '0',
						id : 'recDealCpnNo',
						checked : true,
						listeners : {
							change : function(field, newValue, oldValue) {
								if (newValue) {
									var whtrate = Ext.getCmp('recDealCouponRate');
									whtrate.setValue("");
									whtrate.disable();
									whtrate.allowBlank = true;
									if (calculationtype == "DEAL")
										PurchasesDeal.setMatVal();
									else
										PurchasesDeal.setMatValByMaturity();
									Ext.getCmp('recDealCouponFreq').hide();
									Ext.getCmp('recDealCoupnData').hide();
									Ext.getCmp('recDealCoupnData').disable();
								}
							}
						}
					}, {
						boxLabel : 'Fixed',
						name : 'couponAvailability',
						inputValue : '1',
						id : 'recDealCpnFixcb',
						listeners : {
							change : function(field, newValue, oldValue) {
								if (newValue) {
									Ext.getCmp('recDealCouponRate').setDisabled(false);
									Ext.getCmp('recDealCouponRate').allowBlank = false;
									Ext.getCmp('recDealCouponFreq').show();
									Ext.getCmp('recDealCoupnData').hide();
									Ext.getCmp('recDealCoupnData').disable();
								}
							}
						}
					}, {
						boxLabel : 'Vary',
						name : 'couponAvailability',
						inputValue : '2',
						id : 'recDealCpnVarycb',
						listeners : {
							change : function(field, newValue, oldValue) {
								if (newValue) {
									Ext.getCmp('recDealCouponRate').setDisabled(false);
									Ext.getCmp('recDealCouponRate').allowBlank = false;
									Ext.getCmp('recDealCouponFreq').hide();
									Ext.getCmp('recDealCoupnData').show();
									Ext.getCmp('recDealCoupnData').enable();
								}
							}
						}
					} ]
				}, {
					xtype : 'textfield',
					vtype : 'Rate',
					validateOnBlur : true,
					maskRe : /[\d\%.]/,
					flex : 1,
					padding : '0 5 0 0',
					name : 'couponRate',
					id : 'recDealCouponRate',
					fieldLabel : 'Coupon Rate',
					blankText : 'Coupon Rate is required',
					msgTarget : 'under',
					disabled : true,
					listeners : {
						blur : function() {
							var value = Ext.util.Format.number(this.value.replace(/%/g, ''), '000.00');
							this.setRawValue(value + "%");
						}
					}
				} ]
			}, {
				xtype : 'numberfield',
				minValue : 0,
				labelWidth : 115,
				maxValue : 100,
				decimalPrecision : 0,
				name : 'couponFreq',
				anchor : '50%',
				id : 'recDealCouponFreq',
				fieldLabel : 'Coupon Frequency',
				disabled : true,
				hidden : true,
				allowBlank : false
			}, {
				xtype : 'fieldcontainer',
				layout : 'hbox',
				hidden : true,
				id : 'recDealCoupnData',
				items : [ {
					xtype : 'datefield',
					fieldLabel : 'Coupon Dates',
					id : 'recDealCpnDts',
					minValue : new Date(),
					flex : 1,
					padding : '0 5 0 0',
					labelWidth : 115,
					blankText : 'Please select a Start Date',
					msgTarget : 'under',
					format : 'd/m/Y',
					emptyText : 'DD/MM/YYYY',
					listeners : {
						change : {
							fn : function(object, newVal, oldVal) {
								var recordIndex = cpnDtStore.findBy(function(record, id) {
									if (newVal != null && (record.get('couponDate').getTime() == newVal.getTime())) {
										return true;
									}
									return false;
								});
								if (recordIndex != -1) {
									Ext.MessageBox.alert('Error!', 'Duplicate Entry!!!');
								} else if (newVal == null) {
									Ext.MessageBox.alert('Error', 'Please Select a Start Date');
									console.log("Null value for date field");
								} else if (valDate.getValue() == null || matDate.getValue() == null) {
									Ext.MessageBox.alert('Error!', 'Deal Period not specified!');
								} else if (newVal < valDate.getValue() || newVal > matDate.getValue()) {
									Ext.MessageBox.alert('Error!', 'Coupon Date should be within the Deal Period!');
								} else {
									cpnDtStore.add({
										couponDate : Ext.util.Format.date(newVal, 'd/m/Y')
									});
								}
							}
						}
					}
				}, Ext.create('Ext.grid.Panel', {
					width : 100,
					height : 130,
					flex : 1,
					store : cpnDtStore,
					id : 'recordDealDtStore',
					autoScroll : true,
					columns : [ {
						xtype : 'datecolumn',
						header : 'Coupon Dates',
						dataIndex : 'couponDate',
						format : 'd/m/Y',
						flex : 1
					} ],
					// hidden : true,
					bbar : [ {
						xtype : 'button',
						text : 'Remove',
						handler : function() {
							var pCpnDtStore = Ext.getCmp('recordDealDtStore');
							var sm = pCpnDtStore.getSelectionModel();
							var sel = sm.getSelection();
							var i = 0;
							var currentDate = new Date();
							for (i = 0; i < sel.length; i++) {
								if (sel[i].get("couponDate") > currentDate) {
									pCpnDtStore.store.remove(sel[i]);
								} else {
									Ext.Msg.alert('Error', 'Cannot Remove Previous Dates!');
								}
							}
						}
					} ]
				}) ]
			}, {
				xtype : 'fieldcontainer',
				layout : 'hbox',
				items : [ {
					xtype : 'radiogroup',
					fieldLabel : 'Interest Type',
					labelWidth : 110,
					columns : 2,
					flex : 1,
					columnWidth : 5,
					padding : '0 5 0 0',
					vertical : true,
					disabled : true,
					items : [ {
						boxLabel : 'Fixed',
						id : 'recDealIntTypeFix',
						name : 'interestRate',
						inputValue : 'Fixed',
						checked : true,
						listeners : {
							change : function(field, newValue, oldValue) {
								if (newValue) {
									console.log(newValue);
									Ext.getCmp('recPurchFloatField1').hide();
									Ext.getCmp('recPurchFloatField2').hide();
									Ext.getCmp('recPurchFloatField1').disable();
									Ext.getCmp('recPurchFloatField2').disable();
									Ext.getCmp('RecPurchResetPeriod').allowBlank = true;
									Ext.getCmp('recPurchFloatResetDt').allowBlank = true;
									Ext.getCmp('recPurchFloor').allowBlank = true;
									Ext.getCmp('recPurchCeiling').allowBlank = true;
									Ext.getCmp('RecPurchResetPeriod').disable();
									Ext.getCmp('recPurchFloatResetDt').disable();
									Ext.getCmp('recPurchFloor').disable();
									Ext.getCmp('recPurchCeiling').disable();
								} else {
									console.log(newValue);
									Ext.getCmp('recPurchFloatField1').show();
									Ext.getCmp('recPurchFloatField2').show();
									Ext.getCmp('recPurchFloatField1').enable();
									Ext.getCmp('recPurchFloatField2').enable();
									Ext.getCmp('RecPurchResetPeriod').allowBlank = false;
									Ext.getCmp('recPurchFloatResetDt').allowBlank = false;
									Ext.getCmp('recPurchFloor').allowBlank = false;
									Ext.getCmp('recPurchCeiling').allowBlank = false;
									Ext.getCmp('RecPurchResetPeriod').enable();
									Ext.getCmp('recPurchFloatResetDt').enable();
									Ext.getCmp('recPurchFloor').enable();
									Ext.getCmp('recPurchCeiling').enable();
								}
							}
						}
					}, {
						boxLabel : 'Floating',
						id : 'recDealIntTypeFloat',
						name : 'interestRate',
						inputValue : 'Floating',
						listeners : {
							change : function(field, newValue, oldValue) {
								if (newValue) {
									console.log(newValue);
									Ext.getCmp('recPurchFloatField1').show();
									Ext.getCmp('recPurchFloatField2').show();
									Ext.getCmp('recPurchFloatField1').enable();
									Ext.getCmp('recPurchFloatField2').enable();
									Ext.getCmp('RecPurchResetPeriod').allowBlank = false;
									Ext.getCmp('recPurchFloatResetDt').allowBlank = false;
									Ext.getCmp('recPurchFloor').allowBlank = false;
									Ext.getCmp('recPurchCeiling').allowBlank = false;
									Ext.getCmp('RecPurchResetPeriod').enable();
									Ext.getCmp('recPurchFloatResetDt').enable();
									Ext.getCmp('recPurchFloor').enable();
									Ext.getCmp('recPurchCeiling').enable();
								} else {
									console.log(newValue);
									Ext.getCmp('recPurchFloatField1').hide();
									Ext.getCmp('recPurchFloatField2').hide();
									Ext.getCmp('recPurchFloatField1').disable();
									Ext.getCmp('recPurchFloatField2').disable();
									Ext.getCmp('RecPurchResetPeriod').allowBlank = true;
									Ext.getCmp('recPurchFloatResetDt').allowBlank = true;
									Ext.getCmp('recPurchFloor').allowBlank = true;
									Ext.getCmp('recPurchCeiling').allowBlank = true;
									Ext.getCmp('RecPurchResetPeriod').disable();
									Ext.getCmp('recPurchFloatResetDt').disable();
									Ext.getCmp('recPurchFloor').disable();
									Ext.getCmp('recPurchCeiling').disable();
								}
							}
						}
					} ]
				}, {
					xtype : 'textfield',
					vtype : 'Rate',
					validateOnBlur : true,
					maskRe : /[\d\%.]/,
					flex : 1,
					name : 'rateinterest',
					padding : '0 5 0 0',
					fieldLabel : 'Rate',
					id : 'recPurchInterestRate',
					allowBlank : false,
					blankText : 'Rate is required',
					msgTarget : 'under',
					listeners : {
						blur : function() {
							var value = Ext.util.Format.number(this.value.replace(/%/g, ''), '000.00');
							this.setRawValue(value + "%");
							if (calculationtype == "DEAL")
								PurchasesDeal.setMatVal();
							else
								PurchasesDeal.setMatValByMaturity();
						}
					}
				} ]
			}, {
				xtype : 'fieldcontainer',
				layout : 'hbox',
				id : 'recPurchFloatField1',
				hidden : true,
				items : [ {
					xtype : 'numberfield',
					id : 'RecPurchResetPeriod',
					labelWidth : 115,
					fieldLabel : 'Reset Period',
					name : 'rateResetPeriod',
					flex : 1,
					allowBlank : true,
					minValue : 1,
					decimalPrecision : 0,
					padding : '0 5 0 0'
				}, {
					xtype : 'datefield',
					fieldLabel : 'Reset Date',
					id : 'recPurchFloatResetDt',
					flex : 1,
					allowBlank : true,
					padding : '0 5 0 0',
					format : 'd/m/Y',
					emptyText : 'DD/MM/YYYY',
					minValue : new Date(),
				} ]
			}, {
				xtype : 'fieldcontainer',
				layout : 'hbox',
				id : 'recPurchFloatField2',
				hidden : true,
				items : [ {
					xtype : 'combo',
					labelWidth : 115,
					fieldLabel : 'Bench Mark',
					store : benchMarkStore,
					displayField : 'name',
					valueField : 'name',
					name : 'benchMark',
					id : 'recPurchBench',
					flex : 1.5,
					padding : '0 5 0 0',
					typeAhead : true,
					typeAheadDelay : 100,
					listConfig : {
						loadingText : 'Searching...',
						emptyText : 'No matching posts found.'
					}
				}, {
					xtype : 'numberfield',
					id : 'recPurchFloor',
					minValue : 0,
					maxValue : 100,
					decimalPrecision : 4,
					name : 'floorValue',
					labelWidth : 50,
					allowBlank : true,
					fieldLabel : 'Floor',
					flex : 1,
					padding : '0 5 0 0'
				}, {
					xtype : 'numberfield',
					id : 'recPurchCeiling',
					minValue : 0,
					maxValue : 100,
					decimalPrecision : 4,
					name : 'ceilingValue',
					fieldLabel : 'Ceiling',
					labelWidth : 50,
					flex : 1,
					allowBlank : true,
					padding : '0 5 0 0'
				} ]
			}, {
				xtype : 'fieldcontainer',
				layout : 'hbox',
				items : [ {
					xtype : 'radiogroup',
					fieldLabel : 'Withholding Tax',
					labelWidth : 110,
					columns : 3,
					columnWidth : 5,
					flex : 1,
					padding : '0 5 0 0',
					vertical : true,
					disabled : true,
					items : [ {
						boxLabel : 'No',
						id : 'recDealWhTNo',
						name : 'withholdingTax',
						inputValue : 'No',
						checked : true,
						disabled : true,
						listeners : {
							change : function(field, newValue, oldValue) {
								if (newValue) {
									var whtrate = Ext.getCmp('withholdingTaxRate');
									whtrate.setValue("");
									whtrate.disable();
									whtrate.allowBlank = true;
									PurchasesDeal.setMatVal('');
								} else {
									var whtrate = Ext.getCmp('withholdingTaxRate');
									whtrate.setValue("");
									whtrate.enable();
									whtrate.allowBlank = false;
								}
							}
						}
					}, {
						boxLabel : 'Upfront',
						id : 'recDealWhTUp',
						name : 'withholdingTax',
						inputValue : 'Upfront',
						disabled : true,
						listeners : {
							change : function(field, newValue, oldValue) {
								if (newValue) {
									PurchasesDeal.setMatVal('Upfront');
								}
							}
						}
					}, {
						boxLabel : 'Maturity',
						id : 'recDealWhTMat',
						name : 'withholdingTax',
						inputValue : 'Maturity',
						disabled : true,
						listeners : {
							change : function(field, newValue, oldValue) {
								if (newValue) {
									PurchasesDeal.setMatVal('Maturity');
								}
							}
						}
					} ]
				}, {
					xtype : 'textfield',
					vtype : 'Rate',
					validateOnBlur : true,
					maskRe : /[\d\%.]/,
					flex : 1,
					padding : '0 5 0 0',
					fieldLabel : 'Withholding Tax Rate',
					disabled : true,
					id : 'withholdingTaxRate',
					name : 'withholdingTaxRate',
					listeners : {
						blur : function() {
							var value = Ext.util.Format.number(this.value.replace(/%/g, ''), '000.00');
							this.setRawValue(value + "%");
							if (calculationtype == "DEAL")
								PurchasesDeal.setMatVal();
							else
								PurchasesDeal.setMatValByMaturity();
						}
					}
				} ]
			}, {
				xtype : 'combo',
				store : new Ext.data.Store({
					fields : [ 'dayBasis' ],
					data : [ {
						"dayBasis" : "Act / Act"
					}, {
						"dayBasis" : "Act / 360"
					}, {
						"dayBasis" : "Act / 364"
					}, {
						"dayBasis" : "Act / 365"
					}, {
						"dayBasis" : "30 / 360"
					}, {
						"dayBasis" : "30 / 365"
					} ]
				}),
				displayField : 'dayBasis',
				valueField : 'dayBasis',
				name : 'dayBasis',
				mode : 'local',
				value : 'Act / 365',
				fieldLabel : 'Day Basis',
				labelWidth : 110,
				forceSelection : true,
				disabled : true,
				allowBlank : false,
				id : 'recDealDayBasis',
				anchor : '50%',
				padding : '0 10 0 0',
				listeners : {
					blur : function() {
						if (calculationtype == "DEAL")
							PurchasesDeal.setMatVal();
						else
							PurchasesDeal.setMatValByMaturity();
					}
				}
			}, {
				xtype : 'radiogroup',
				columns : 2,
				anchor : '50%',
				vertical : true,
				disabled : true,
				labelWidth : 170,
				fieldLabel : 'Interest Calculation Method',
				items : [ {
					boxLabel : 'Straight',
					name : 'intCalMethod',
					checked : true,
					id : 'recDealIntCalStr',
					inputValue : 'straight',
				}, {
					boxLabel : 'Discounted',
					name : 'intCalMethod',
					id : 'recDealIntCalDis',
					inputValue : 'discounted',
				} ]
			}, {
				xtype : 'fieldcontainer',
				layout : 'hbox',
				items : [ {
					xtype : 'checkboxfield',
					boxLabel : 'Scripts',
					name : 'scripts',
					inputValue : 1,
					id : 'recDealScripts',
					disabled : true,
					padding : '0 10 0 0',
					flex : 0.5
				}, {
					xtype : 'checkboxfield',
					boxLabel : 'Denominals',
					name : 'denominals',
					inputValue : 1,
					id : 'recDealdenominals',
					disabled : true,
					padding : '0 10 0 0',
					flex : 0.5
				}, {
					xtype : 'textfield',
					padding : '0 5 0 0',
					flex : 1,
					name : 'denominalMinVal',
					id : 'recDealDenominamMinVal',
					fieldLabel : 'Minimum Value',
					disabled : true,
					allowBlank : false
				} ]
			} ]
		} ]
	});
};

PurchasesDeal.getCenterPanel = function() {

	var basic = PurchasesDeal.getBasicFieldSet();
	var instrument = PurchasesDeal.getInstrumentFieldSet();
	var deal = PurchasesDeal.getDealFieldSet();
	var insDtl = PurchasesDeal.getInstrumentDetailFieldSet();

	CommenStore.settlmentStore.load();
	CommenStore.dealersStore.load();
	CommenStore.delevaryMethodStore.load();

	formPanel = Ext.create('Ext.form.FormPanel', {
		title : 'New Purchase Record',
		id : 'recPurchaseMainPanel',
		bodyPadding : '20',
		autoScroll : true,
		frame : true,
		defaults : {
			anchor : '72%'
		},
		fieldDefaults : {
			labelAlign : 'left'
		},
		items : [ {
			xtype : 'fieldcontainer',
			items : [ {
				xtype : 'triggerfield',
				id : 'recPurchTrigField',
				triggerCls : 'x-form-search-trigger',
				width : 300,
				style : 'float:right;',
				emptyText : 'Search for a Purchase',
				onTriggerClick : function() {
					var resultWindow = null;
					var searchResult = Ext.create('Ext.data.Store', {
						fields : [ 'id', 'dealCode', 'name', 'status' ]
					});
					var TrigField = Ext.ComponentQuery.query('#recPurchTrigField')[0];

					Ext.Ajax.request({
						url : 'getPurchases.action',
						params : {
							query : TrigField.getValue()
						},
						success : function(response) {
							var obj = Ext.decode(response.responseText);
							searchResult.loadRawData(obj.deals);
						}
					});
					if (!resultWindow) {
						resultWindow = Ext.create('Ext.window.Window', {
							title : 'Purchase Deals',
							height : 330,
							frame : true,
							width : 500,
							constrain : true,
							resizable : false,
							layout : {
								type : 'fit'
							},
							items : [ {
								xtype : 'gridpanel',
								defaults : {
									anchor : '100%'
								},
								store : searchResult,
								columns : [ {
									text : 'Deal Code',
									dataIndex : 'dealCode',
									flex : 1
								}, {
									text : 'Name',
									dataIndex : 'name',
									flex : 2
								}, {
									text : 'Status',
									dataIndex : 'status',
									flex : 1
								} ],
								listeners : {
									itemdblclick : function(view, rec, item, index, eventObj) {
										var findId = rec.get('id');
										var formPanl = Ext.getCmp('recPurchaseMainPanel');
										formPanl.getForm().reset();
										Ext.data.StoreManager.lookup('couponDatesStore').removeAll();
										formPanl.setLoading('Receiving data...', formPanl.getForm());
										Ext.Ajax.request({
											url : 'getPurchase.action',
											params : {
												id : findId
											},
											success : function(response) {
												var obj = Ext.decode(response.responseText);
												searchDeal.loadRawData(obj.dealDtos);
												var rec = searchDeal.getAt(0);
												formPanel.loadRecord(rec);

												var lblDealID = Ext.getCmp('recDealDealID');
												lblDealID.show();
												lblDealID.setText('Deal ID: ' + rec.get('dealCode'));

												var lblDealStatus = Ext.getCmp('recDealStatusLbl');
												lblDealStatus.show();
												lblDealStatus.setValue('Status: ' + rec.get('status'));

												if (rec.get('params') != null) {
													Ext.getCmp('recPurchParamLbl').setText(rec.get('params'));
												}

												if (rec.get('status') === 'Initial') {
													Ext.getCmp('recPurchUpdateBtn').enable();
													Ext.getCmp('recPurchSaveBtn').disable();
												} else {
													Ext.getCmp('recPurchUpdateBtn').disable();
													Ext.getCmp('recPurchSaveBtn').disable();
												}

												formPanl.setLoading(false);

											},
											failure : function(form, action) {
												formPanl.setLoading(false);
											}
										});
										resultWindow.close();
									}
								}
							} ]
						});
					}
					if (resultWindow.isVisible()) {
						resultWindow.close();
					} else {
						resultWindow.show();
					}
				}
			} ]
		}, instrument, basic, deal, insDtl ],
		buttonAlign : 'center',
		buttons : [ {
			text : 'Cancel',
			handler : function() {
				App.Core.removeScreen();
			}
		}, {
			text : 'Reset',
			handler : function() {
				Ext.getCmp('recPurchaseMainPanel').getForm().reset();

				Ext.getCmp('recPurchUpdateBtn').disable();
				Ext.getCmp('recPurchSaveBtn').enable();
				Ext.data.StoreManager.lookup('couponDatesStore').removeAll();
				// Ext.ComponentQuery.query('#recPurchDuration')[0].setText('');
				Ext.ComponentQuery.query('#recDealDealID')[0].setText('');
				Ext.ComponentQuery.query('#recDealStatusLbl')[0].setValue('');
				// Ext.ComponentQuery.query('#recDealListedLabel')[0].setText('');
				calculationtype = "DEAL";
				// Ext.ComponentQuery.query('#recDealInstrumentType')[0].enable();
				// Ext.ComponentQuery.query('#recDealInstrumentCodeCombo')[0].enable();
				// Ext.ComponentQuery.query('#recDealInstrumentCodeText')[0].enable();
				// Ext.ComponentQuery.query('#recPurchaseFund')[0].enable();

			}
		}, {
			text : 'Save',
			id : 'recPurchSaveBtn',
			itemId : 'saveButton',
			handler : function() {
				var form = this.up('form').getForm();
				form.url = 'addNewDeal.action';
				if (form.isValid()) {
					formPanel.setLoading('Saving...');
					var couponDates = '';
					Ext.data.StoreManager.lookup('couponDatesStore').each(function(r) {
						couponDates += Ext.util.Format.date(r.get('couponDate')) + ';';
					});
					var rstDt = Ext.ComponentQuery.query('#recPurchFloatResetDt')[0];
					var valueDtField = Ext.ComponentQuery.query('#recPurchValueDt')[0];
					var maturityDtField = Ext.ComponentQuery.query('#recPurchMaturityDt')[0];
					var params = (Ext.ComponentQuery.query('#recPurchParamLbl')[0]).text;

					form.submit({
						params : {
							'couponDates' : couponDates,
							'resetDate' : Ext.util.Format.date(rstDt.getValue()),
							'valueDate' : Ext.util.Format.date(valueDtField.getValue()),
							'maturityDate' : Ext.util.Format.date(maturityDtField.getValue()),
							'user' : 'createdUser',
							'params' : params
						},
						success : function(form, action) {
							form.reset();
							Ext.getCmp('recPurchUpdateBtn').disable();
							Ext.getCmp('recPurchSaveBtn').enable();
							Ext.data.StoreManager.lookup('couponDatesStore').removeAll();
							Ext.ComponentQuery.query('#recDealDealID')[0].setText('');
							Ext.ComponentQuery.query('#recDealStatusLbl')[0].setValue('');
							calculationtype = "DEAL";
							Ext.Msg.alert('Success', action.result.name + ' is created.<br> Deal Code is <b>' + action.result.dealCode + '</b>');
							formPanel.setLoading(false);
						},
						failure : function(form, action) {
							Ext.Msg.alert('Failed', 'There is some error returned from the server.<br><b>' + action.result.status + '</b>');
							formPanel.setLoading(false);
						}
					});
				} else {
					Ext.Msg.alert('Failed', "Form Incomplete. Please check!");
				}
			}
		}, {
			text : 'Update',
			id : 'recPurchUpdateBtn',
			itemId : 'updateButton',
			disabled : true,
			handler : function() {
				var form = this.up('form').getForm();

				form.url = 'updatePurchase.action';

				var tempInsTypeCmb = Ext.ComponentQuery.query('#recDealInstrumentType')[0];
				var tempInsType = tempInsTypeCmb.getValue();
				tempInsTypeCmb.select(tempInsType);

				if (form.isValid()) {
					formPanel.setLoading('Updating...');
					var couponDates = '';
					Ext.data.StoreManager.lookup('couponDatesStore').each(function(r) {
						couponDates += Ext.util.Format.date(r.get('couponDate')) + ';';
					});
					var rstDt = Ext.ComponentQuery.query('#recPurchFloatResetDt')[0];
					var valueDtField = Ext.ComponentQuery.query('#recPurchValueDt')[0];
					var maturityDtField = Ext.ComponentQuery.query('#recPurchMaturityDt')[0];
					var dealCode = Ext.ComponentQuery.query('#recDealDealID')[0].text.substr(9);
					var params = (Ext.ComponentQuery.query('#recPurchParamLbl')[0]).text;

					form.submit({
						params : {
							'couponDates' : couponDates,
							'resetDate' : Ext.util.Format.date(rstDt.getValue()),
							'valueDate' : Ext.util.Format.date(valueDtField.getValue()),
							'maturityDate' : Ext.util.Format.date(maturityDtField.getValue()),
							'dealCode' : dealCode,
							'user' : 'updateUser',
							'params' : params
						},
						success : function(form, action) {
							form.reset();
							Ext.getCmp('recPurchUpdateBtn').disable();
							Ext.getCmp('recPurchSaveBtn').enable();
							Ext.data.StoreManager.lookup('couponDatesStore').removeAll();
							Ext.ComponentQuery.query('#recDealDealID')[0].setText('');
							Ext.ComponentQuery.query('#recDealStatusLbl')[0].setValue('');
							calculationtype = "DEAL";
							Ext.Msg.alert('Success', action.result.name + ' is Updated.<br> Deal Code is <b>' + action.result.dealCode + '</b>');
							formPanel.setLoading(false);
						},
						failure : function(form, action) {
							Ext.Msg.alert('Failed', 'There is some error returned from the server.<br><b>' + action.result.status + '</b>');
							formPanel.setLoading(false);
						}
					});

				} else {
					Ext.Msg.alert('Failed', "Form Incomplete. Please check!");
				}
			}
		} ],
		listeners : {
			render : function(p) {
				Ext.Ajax.request({
					url : 'getBankHoliday.action',
					success : function(response) {
						var obj = Ext.decode(response.responseText);
						HolidayCalendar.holiday_store.removeAll();
						HolidayCalendar.holiday_store.loadRawData(obj.calendarDtos);
						HolidayCalendar.holiday_store.each(function(record) {
							inv_disableDates.push(record.get('date'));
						});
						Ext.getCmp('recPurchMaturityDt').setDisabledDates(inv_disableDates);
						Ext.getCmp('recPurchValueDt').setDisabledDates(inv_disableDates);
					}
				});
			}
		}
	});

	return formPanel;
};
PurchasesDeal.setInstrumentValue = function(record) {

	var dfValDate = Ext.getCmp('recPurchValueDt');
	dfValDate.format = 'd/m/Y';
	dfValDate.setValue(record.get('valueDate'));

	var dfMatDate = Ext.getCmp('recPurchMaturityDt');
	dfMatDate.format = 'd/m/Y';
	dfMatDate.setValue(record.get('maturityDate'));

	Ext.getCmp('recDealCouponRate').setValue(record.get('couponRate'));
	Ext.getCmp('recDealDenominamMinVal').setValue(record.get('minDenominal'));

};
PurchasesDeal.getRollOverDeal = function(instumentType, fund, dealCode, issuer, valueDate, principleValue) {

	var panel = PurchasesDeal.getCenterPanel();
	var tmpInsTypeStore = Ext.data.StoreManager.lookup('recPurchInsTypeStore');
	var tmpFundStore = Ext.data.StoreManager.lookup('dealFundsStore');
	var tmpPrimeDealerStore = Ext.data.StoreManager.lookup('primaryDealersStore');
	var tmpIssuerStore = Ext.data.StoreManager.lookup('issuersStore');

	var tmpPrimDealerCmb = Ext.getCmp('recordDealPrimDealer');
	var tmpIssuerCmb = Ext.getCmp('recordDealIssuer');
	var insTypeCmb = Ext.getCmp('recDealInstrumentType');
	var fundCmb = Ext.getCmp('recPurchaseFund');
	var tmpValDt = Ext.getCmp('recPurchValueDt');
	var tmpDealValue = Ext.getCmp('recPurchDealVal');
	var paramLabel = Ext.getCmp('recPurchParamLbl');

	Ext.Ajax.request({
		url : 'getInstrumentTypes.action',
		success : function(response) {
			var obj = Ext.decode(response.responseText);
			tmpInsTypeStore.loadRawData(obj.instrumentTypeList);
			insTypeCmb.setValue(tmpInsTypeStore.getAt(tmpInsTypeStore.find('instrumentName', instumentType)).get('id'));
			var insTypeRecord = tmpInsTypeStore.findRecord('instrumentName', instumentType);
			insTypeCmb.fireEvent('select', insTypeCmb, insTypeRecord);
			Ext.Ajax.request({
				url : 'getFundsForDealInsType.action',
				params : {
					querry : 'PURCH',
					querryTwo : insTypeCmb.getValue()
				},
				success : function(response) {
					var obj = Ext.decode(response.responseText);
					Ext.data.StoreManager.lookup('dealFundsStore').loadRawData(obj.fundList);
					fundCmb.setValue(tmpFundStore.getAt(tmpFundStore.find('fundCode', fund)).get('id'));
					if (!tmpPrimDealerCmb.isDisabled()) {
						tmpPrimDealerCmb.setValue(tmpPrimeDealerStore.getAt(tmpPrimeDealerStore.find('code', issuer)).get('id'));
					} else {
						tmpIssuerCmb.setValue(tmpIssuerStore.getAt(tmpIssuerStore.find('code', issuer)).get('id'));
					}
				},
				failure : function(response) {
					Ext.Msg.alert('Error!', 'Failed to Load Fund!');
				}
			});
		},
		failure : function(response) {
			Ext.Msg.alert('Error!', 'Failed to Load Instrument Type!');
		}
	});
	tmpValDt.setValue(valueDate);
	tmpDealValue.setValue(principleValue);
	paramLabel.setText(dealCode);

	return panel;
};

PurchasesDeal.setMatVal = function(withholdingTaxTypeFrom) {

	// Ext.ComponentQuery.query('#recDealMaturityValue')[0].reset();
	console.log('Start SetMatVal');

	var withholdingTaxType = withholdingTaxTypeFrom;

	var insType = Ext.ComponentQuery.query('#recDealInstrumentType')[0].getValue();
	if (insType == null)
		return;

	var valueDt = Ext.ComponentQuery.query('#recPurchValueDt')[0].getValue();
	if (valueDt == null)
		return;

	var maturityDt = Ext.ComponentQuery.query('#recPurchMaturityDt')[0].getValue();
	if (maturityDt == null)
		return;

	if (withholdingTaxType == null || withholdingTaxType == '')
		withholdingTaxType = Ext.ComponentQuery.query('#recDealWhTMat')[0].getGroupValue();
	var withholdingTaxRate = Ext.ComponentQuery.query('#withholdingTaxRate')[0].getValue();

	if (withholdingTaxType == null || withholdingTaxType == '') {
		return;
	} else if (withholdingTaxType == 'Maturity' || withholdingTaxType == 'Upfront') {
		if (withholdingTaxRate == null || withholdingTaxRate == '')
			return;
	}

	var principleValueField = Ext.ComponentQuery.query('#recPurchDealVal')[0];
	var principleValue;

	principleValue = principleValueField.getValue();
	if (principleValue == '' || principleValue == null)
		return;

	var interestRate = Ext.ComponentQuery.query('#recPurchInterestRate')[0].getValue();
	if (interestRate == null || interestRate == '')
		return;

	var dayBasis = Ext.ComponentQuery.query('#recDealDayBasis')[0].getValue();
	if (dayBasis == null)
		return;

	console.log('COMPLETED');
	Ext.Ajax.request({
		url : 'evalPurchase.action',
		params : {
			'insType' : insType,
			'valueDate' : Ext.util.Format.date(valueDt),
			'maturityDate' : Ext.util.Format.date(maturityDt),
			'withholdingTax' : withholdingTaxType,
			'withholdingTaxRate' : withholdingTaxRate,
			'dealValue' : principleValue,
			'maturityValue' : 0,
			'dayBasis' : dayBasis,
			'rateinterest' : interestRate
		},
		success : function(response) {
			var obj = Ext.decode(response.responseText);
			Ext.ComponentQuery.query('#recDealMaturityValue')[0].setValue(Ext.util.Format.number(obj.maturityValue.replace(/,/g, ''), '0,000.0000'));
		},
		failure : function(response) {
			alert('Error in Maturity Value Calculation : ' + obj.status);
			Ext.ComponentQuery.query('#recDealMaturityValue')[0].reset();
		}
	});
};

PurchasesDeal.setMatValByMaturity = function(withholdingTaxTypeFrom) {

	console.log('Start SetMatVal Maturity');

	var withholdingTaxType = withholdingTaxTypeFrom;

	var insType = Ext.ComponentQuery.query('#recDealInstrumentType')[0].getValue();
	if (insType == null)
		return;

	var valueDt = Ext.ComponentQuery.query('#recPurchValueDt')[0].getValue();
	if (valueDt == null)
		return;

	var maturityDt = Ext.ComponentQuery.query('#recPurchMaturityDt')[0].getValue();
	if (maturityDt == null)
		return;

	if (withholdingTaxType == null || withholdingTaxType == '')
		withholdingTaxType = Ext.ComponentQuery.query('#recDealWhTMat')[0].getGroupValue();
	var withholdingTaxRate = Ext.ComponentQuery.query('#withholdingTaxRate')[0].getValue();

	if (withholdingTaxType == null || withholdingTaxType == '') {
		return;
	} else if (withholdingTaxType == 'Maturity' || withholdingTaxType == 'Upfront') {
		if (withholdingTaxRate == null || withholdingTaxRate == '')
			return;
	}

	var maturityValueField = Ext.ComponentQuery.query('#recDealMaturityValue')[0];
	var maturityValue;

	maturityValue = maturityValueField.getValue();
	if (maturityValue == '' || maturityValue == null)
		return;

	var interestRate = Ext.ComponentQuery.query('#recPurchInterestRate')[0].getValue();
	if (interestRate == null || interestRate == '')
		return;

	var dayBasis = Ext.ComponentQuery.query('#recDealDayBasis')[0].getValue();
	if (dayBasis == null)
		return;
	console.log('COMPLETED');
	Ext.Ajax.request({
		url : 'evalPurchaseDealValue.action',
		params : {
			'insType' : insType,
			'valueDate' : Ext.util.Format.date(valueDt),
			'maturityDate' : Ext.util.Format.date(maturityDt),
			'withholdingTax' : withholdingTaxType,
			'withholdingTaxRate' : withholdingTaxRate,
			'dealValue' : 0,
			'maturityValue' : maturityValue,
			'dayBasis' : dayBasis,
			'rateinterest' : interestRate
		},
		success : function(response) {
			var obj = Ext.decode(response.responseText);
			Ext.ComponentQuery.query('#recPurchDealVal')[0].setValue(Ext.util.Format.number(obj.dealValue.replace(/,/g, ''), '0,000.0000'));
		},
		failure : function(response) {
			alert('Error in Maturity Value Calculation : ' + obj.status);
			Ext.ComponentQuery.query('#recPurchDealVal')[0].reset();
		}
	});
};